package com.hncj.yqfk.aop;



import com.hncj.yqfk.entity.Log;
import com.hncj.yqfk.ldao.Log_Dao;
import com.hncj.yqfk.service.impl.UserServiceImp;
import com.hncj.yqfk.utils.IPUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


@Aspect
@Component
public class LogAspect {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Pointcut("@annotation(com.hncj.yqfk.aop.LogAnnotation)")
    public void LogPointcut(){
    }


    @Autowired
    private UserServiceImp usi;
    @Autowired
    Log_Dao log_dao;
    @AfterReturning(returning = "result" ,value = "LogPointcut()")
    public void saveLog(JoinPoint joinPoint, Object result) throws Throwable{
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        try {
            Log log= new Log();
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取切入点所在的方法
            Method method = signature.getMethod();
            //获取操作
            LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
            if (annotation != null) {
                log.setModel(annotation.operModul());
                log.setType(annotation.operType());
                log.setDescription(annotation.operDesc());
            }
            //操作时间
            log.setOperation_time(Timestamp.valueOf(sdf.format(new Date())));
            //操作用户
            log.setUser_code("管理员");
//            log.setUser_code(request.getHeader("user_code"));
//            log.setUser_code("管理员:"+result);
            //操作IP
            log.setIp(IPUtil.getIpAdrress(request));
            //返回值信息
            log.setResult("操作成功!");
            //保存日志
            log_dao.save(log);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

